package main

import (
	"flag"
	"fmt"
	"io"
	"net"
	"os"
)

type Client struct {
	ServerIp   string
	ServerPort int
	Name       string
	conn       net.Conn
}

func NewClient(serverIp string, serverPort int) *Client {
	client := &Client{
		ServerIp:   serverIp,
		ServerPort: serverPort,
	}

	conn, err := net.Dial("tcp", fmt.Sprintf("%s:%d", serverIp, serverPort))
	if err != nil {
		fmt.Println("net.Dial error:", err)
		return nil
	}

	client.conn = conn

	return client
}

func (client *Client) DealResponse() {
	// blocking listen permanently
	io.Copy(os.Stdout, client.conn)

	/* the same as this code
	buf := make([]byte, 4096)
	for {
		n, err := client.conn.Read(buf)

		if err != nil && err != io.EOF {
			fmt.Println("Conn Read err:", err)
			return
		}

		msg := string(buf[:n-1])
		fmt.Println(msg)
	}
	*/
}

func (client *Client) Start() {
	for {
		var msg string
		_, err := fmt.Scan(&msg)
		if err != nil {
			fmt.Println("Scanln err:", err)
			return
		}
		
		client.conn.Write([]byte(msg + "\n"))  // if there is no a "\n", output will be wrong
	}
}

var serverIp string
var serverPort int

func init() {
	flag.StringVar(&serverIp, "ip", "127.0.0.1", "设置服务器ip地址")
	flag.IntVar(&serverPort, "port", 9999, "设置服务器端口")
}

func main() {
	flag.Parse() // parse cmd
	client := NewClient("127.0.0.1", 9999)
	if client == nil {
		fmt.Println(">>>>>> 连接服务失败...")
		return
	}
	fmt.Println(">>>>>> 成功连接")

	go client.DealResponse()

	client.Start()
}
